package server.loader;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.mapper.Context;
import server.mapper.Host;
import servlet.StaticResourceUtil;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by louisyuu on 2020/4/2 下午5:28
 */
public class ServerLoader {


    public void loadServer() {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("conf/server.xml");

        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(inputStream);
            Element rootElement = document.getRootElement();

            /**
             * <Host name="localhost" appBase="webapps">
             */
            Element hostElement = (Element) rootElement.selectSingleNode("//Host");
            String host = hostElement.attributeValue("name");
            String appBase = hostElement.attributeValue("appBase");

            Host hostObj = new Host();
            hostObj.setHost(host);
            hostObj.setAppBase(appBase);

            String absolutePath = StaticResourceUtil.getAbsolutePath(appBase);
            hostObj.setAppBaseAbsolutePath(absolutePath);


            /**
             * <Context docBase="/Users/yingdian/web_demo" path="/web-demo2"></Context>
             *
             *
             * <Context docBase="/Users/yingdian/web_demo" path="/web-demo1"></Context>
             */
            List<Element> elements = document.selectNodes("//Context");

            List<Context> contexts = new ArrayList<>();

            for (Element element : elements) {
                String docBase = element.attributeValue("docBase");
                String path = element.attributeValue("path");
                Context context = new Context(docBase, path);
                contexts.add(context);
            }
            hostObj.setContexts(contexts);


            Host.hostMap.put(hostObj.getHost(), hostObj);
        } catch (DocumentException e) {
            e.printStackTrace();
        }


    }
}
